import request from "./request.js"
import {URL_USER_INFO} from './urls.js';

function refreshJwtToken() {

	let jwtToken = uni.getStorageSync('jwtToken');
	if (!jwtToken) {
		uni.removeStorageSync('jwtToken');
		uni.removeStorageSync('userInfo');


		return;
	}
	this.$request({
		// todo 这个地址需要修改下
		url: URL_USER_INFO,
		data: {},
		method: 'GET'
	}).then(res => {
		console.log(res.data);
		if (res.data.errorCode === 0) {
			uni.setStorageSync('jwtToken', res.data.jwtToken);
			uni.setStorageSync('userInfo', res.data.userView);
		} else {
			uni.removeStorageSync('jwtToken');
			uni.removeStorageSync('userInfo');

		}
	})
}

function showToast(title) {
	uni.showToast({
		title: title,
		duration: 1000,
		mask: true,
		icon: 'none'
	});
}

function gotoLoginPage() {
	// #ifdef MP-WEIXIN
	var url = '/pages/myprofile-login/myprofile-wechatapp-login';
	uni.navigateTo({
		url: url
	})
	return;
	// #endif


	// #ifdef MP-ALIPAY
	var url = '/pages/myprofile-login/myprofile-alipay-login';
	uni.navigateTo({
		url: url
	})
	return;
	// #endif


	// #ifdef H5
	// var url = '/pages/myprofile-login/myprofile-h5-login';
	// uni.navigateTo({
	// 	url: url
	// })
	return;
	// #endif
}



function getUserInfo() {
	const userInfo = uni.getStorageSync('userInfo');
	if (userInfo) {
		return userInfo;
	}
	return '';
}

function getUserId() {
	const userInfo = uni.getStorageSync('userInfo');
	if (userInfo) {
		return userInfo.id;
	}
	return 0;
}

function formatCount(num) {
	let digits = 1;
	const si = [{
			value: 1,
			symbol: ""
		},
		{
			value: 1E3,
			symbol: "K"
		},
		{
			value: 1E6,
			symbol: "M"
		},
		{
			value: 1E9,
			symbol: "G"
		},
		{
			value: 1E12,
			symbol: "T"
		},
		{
			value: 1E15,
			symbol: "P"
		},
		{
			value: 1E18,
			symbol: "E"
		}
	];
	const rx = /\.0+$|(\.[0-9]*[1-9])0+$/;
	let i;
	for (i = si.length - 1; i > 0; i--) {
		if (num >= si[i].value) {
			break;
		}
	}
	return (num / si[i].value).toFixed(digits).replace(rx, "$1") + si[i].symbol;
}

module.exports = {
	refreshJwtToken,
	getUserInfo,
	getUserId,
	showToast,
	gotoLoginPage,
	formatCount,
}
